#!/usr/bin/env python3
import json
import sys

dirpath="/Volumes/Coding/hulk_robot_test/openEuler"

COM_FILE = f'{dirpath}/conf/committers.json'
KERNEL_FILE = "filelist.log"

committer_conf = {}


def get_committer_files(node, prefix=""):
    files = []
    files.append([prefix, node.get("owner", [])])

    if len(node.get("children", {})) == 0:
        return files

    for ch in list(node["children"].keys()):
        files += get_committer_files(node["children"][ch], prefix + "/" + ch)

    return files


def lookup_committer(path):
    committers = []
    committers.append(committer_conf["/"]["owner"])
    curr = committer_conf["/"]["children"]

    paths = path.split("/")
    for path in paths:
        if path not in curr:
            break
        else:
            owner = curr[path].get("owner", [])
            if len(owner) == 0:
                pass
            else:
                if "UNMAINTAINED" in committers[-1]:
                    committers.pop()
                if committers[-1] != owner:
                    committers.append(owner)
            curr = curr[path].get("children", {})

    committers.reverse()
    return committers


def flatten(nested_list):
    res = []
    for item in nested_list:
        if isinstance(item, list):
            res.extend(flatten(item))
        else:
            res.append(item)
    return res


def committers_json_to_csv():
    files = get_committer_files(committer_conf["/"], "")
    for f, owners in files:
        print(f"{f}\t{','.join(owners)}")


def check_current_committers():
    with open(KERNEL_FILE, 'r') as f:
        for line in f.readlines():
            line = line.strip().strip('/')
            if not line:
                continue
            owners = lookup_committer(line)
            print(f"/{line}\t{','.join(flatten(owners))}")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: check-committers.py [json2csv|status]")
        sys.exit(1)
    
    with open(COM_FILE, 'r') as f:
        ctx = f.read()
        committer_conf = json.loads(ctx)

    if sys.argv[1] == "json2csv":
        committers_json_to_csv()
    elif sys.argv[1] == "status":
        check_current_committers()
